package com.mkjb.controller.validator;

import com.mkjb.dto.ChangePasswordDto;
import com.mkjb.entity.User;
import com.mkjb.utils.SessionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import java.util.Objects;


/**
 * Created by DingJie on 2017/5/17.
 */
@Component
public class ChangePasswordDtoValidator implements Validator {

    @Override
    public boolean supports(Class<?> aClass) {
        return ChangePasswordDto.class.equals(aClass);
    }

    @Override
    public void validate(Object o, Errors errors) {
        ChangePasswordDto changePasswordDto = (ChangePasswordDto) o;
        validatePassword(changePasswordDto, errors);
    }

    private void validatePassword(ChangePasswordDto changePasswordDto, Errors errors) {
        User user = (User) SessionUtils.getCurrentUserAccount();
        if (!Objects.equals(changePasswordDto.getOldPassword(), user.getPassword())) {
            errors.rejectValue("oldPassword", null, "原始密码错误");
        }
        if (StringUtils.isEmpty(changePasswordDto.getNewPassword()) || StringUtils.isEmpty(changePasswordDto.getConfirmPassword())) {
            errors.rejectValue("newPassword", null, "新密码不能为空");
            errors.rejectValue("confirmPassword", null, "确认密码不能为空");

        }
        if (!Objects.equals(changePasswordDto.getNewPassword(), changePasswordDto.getConfirmPassword())) {
            errors.rejectValue("newPassword", null, "密码不一致");
            errors.rejectValue("confirmPassword", null, "密码不一致");
        }
    }
}
